package com.beamfield.controller.manage.auth;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.beamfield.model.BeamField;
import com.beamfield.modelVo.BeamFieldVo;
import com.beamfield.modelVo.RoleModelTreeVo;
import com.beamfield.service.manage.auth.AdminInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.beamfield.common.ApiResult;
import com.beamfield.common.CommonUtils;
import com.beamfield.enums.HttpResultEnum;
import com.beamfield.model.AdminInfo;
import com.beamfield.service.manage.sys.BeamFieldService;
import com.beamfield.service.manage.auth.AuthService;

import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/cms")
public class LoginController {

	@Value("${session.user}")
	private String user;

	@Value("${session.uname}")
	private String uName;

	@Value("${session.beam}")
	private String beam;

	@Value("${session.beam_name}")
	private String beamName;


	@Resource
	BeamFieldService beamFieldService;

	@Resource
	AuthService authService;

	@Resource
    private AdminInfoService adminInfoService;


	/**
	 * 登录逻辑
	 * @return
	 */
	@RequestMapping("/doLogin")
	@ResponseBody
	public ApiResult doLogin(HttpSession session, String loginName, String password){
		if(CommonUtils.isEmptyString(loginName)||CommonUtils.isEmptyString(password)){
			return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(),HttpResultEnum.MIS_PARAM.getMessage());
		}
		AdminInfo admin = authService.getAdminByLogin(loginName, null);
		if(admin==null){
			return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(),"账号密码错误");
		}else{
			if(!Objects.equals(CommonUtils.MD5(CommonUtils.MD5(password)+loginName),admin.getPwd_eight())){
				return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(),"账号密码错误");
			}else{
				session.setAttribute(user,admin.getAdmin_id());
				session.setAttribute(uName,admin.getReal_name());

				String beamId = admin.getBeam_id();
				List<String> beamIdList = Arrays.stream(beamId.split(",")).filter(StringUtils::isNotEmpty).collect(Collectors.toList());
				if(beamIdList.size() == 1){
					BeamField beamField = beamFieldService.getBeamFieldVoByBeamId(Long.parseLong(beamIdList.get(0)));
					session.setAttribute(beam,beamField.getBeam_id());
					session.setAttribute(beamName,beamField.getName());

				}else{
					List<BeamFieldVo> beamFieldByBeamIdList = beamFieldService.getBeamFieldByBeamIdList(beamIdList);
					return new ApiResult("203","Need choose BeamField!",beamFieldByBeamIdList);
				}
			}
		}
		return new ApiResult(HttpResultEnum.SUCCESS.getCode(), HttpResultEnum.SUCCESS.getMessage(), admin.getLast_theme());
	}

	/**
	 * 系统管理装饰器模板页面
	 * @return
	 */
	@RequestMapping("/login")
	public ModelAndView login(HttpSession session){

		ModelAndView mv = new ModelAndView();
		Long userid = (Long) session.getAttribute(user);
		if(userid != null && userid != 0L){
			session.removeAttribute(user);
		}
		 return mv;
	}

	/**
	 * 系统管理装饰器模板页面
	 * @return
	 */
	@RequestMapping(value = {"/index"})
	public ModelAndView index(HttpSession session){
		ModelAndView mv = new ModelAndView();
		Long userid = (Long) session.getAttribute(user);
		if(userid==null||userid==0){
			mv.setViewName("redirect:/cms/login");
			return mv;
		}
		 return mv;
	}

	/**
	 * 系统管理装饰器模板页面
	 * @return
	 */
	@RequestMapping("/indext")
	public ModelAndView indext(HttpSession session){
		ModelAndView mv = new ModelAndView();
		Long userid = (Long) session.getAttribute(user);
		if(userid==null||userid==0){
			mv.setViewName("redirect:/cms/login");
			return mv;
		}
		return mv;
	}

	/**
	 * 获取可以选择的梁场列表
	 */
	@RequestMapping("/beamfieldList")
	@ResponseBody
	public ApiResult beamfieldList(){
		return new ApiResult(beamFieldService.getAllBeamNameAndId());
	}

	@RequestMapping("/getMainMenu")
	@ResponseBody
	public ApiResult getMainMenu(HttpSession session, HttpServletRequest request){
		Long userid = (Long) session.getAttribute(user);
		String platform = request.getParameter("platform");
		List<RoleModelTreeVo> menu = authService.getAllMenu(userid, platform);
		return new ApiResult(menu);
	}


	@RequestMapping("/getAdminInfo")
	@ResponseBody
	public ApiResult getAdminInfo(HttpSession session){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("userName",session.getAttribute(uName));
		map.put("beamName",session.getAttribute(beamName));
		return new ApiResult(map);
	}

	@RequestMapping("/getMainMenuOne")
	@ResponseBody
	public ApiResult getMainMenuOne(HttpSession session, HttpServletRequest request){
		Long userid = (Long) session.getAttribute(user);
		String platform = request.getParameter("platform");
		List<RoleModelTreeVo> allMenu = authService.getMenuOne(userid, platform);
		return new ApiResult(allMenu);
	}


	@RequestMapping("/getMainMenuChild")
	@ResponseBody
	public ApiResult getMainMenuChild(HttpSession session,Integer type,Integer modelid, HttpServletRequest request){
		Long userid = (Long) session.getAttribute(user);
		String platform = request.getParameter("platform");
		if(type==0){
			return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(),HttpResultEnum.MIS_PARAM.getMessage());
		}
		List<RoleModelTreeVo> allMenu = authService.getMenuChild(userid,type,modelid, platform);
		return new ApiResult(allMenu);
	}

	/**
	 * 获取登录用户按钮权限信息
	 * @param modelId
	 * @return
	 */
	@RequestMapping(value = "/fetchLoginUserBtnPer", method = RequestMethod.GET)
	@ResponseBody
	public ApiResult fetchLoginUserBtnPer(HttpSession session, @RequestParam("modelId") String modelId){
		if(StringUtils.isEmpty(modelId)){
			return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
		}
		Long userId = (Long) session.getAttribute(user);
		try {
			return this.authService.getLoginUserBtnPer(userId, modelId);
		}catch (Exception e){
			e.printStackTrace();
			return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
		}
	}

	/**
	 * 用户切换主题时更新
	 * @return
	 */
	@RequestMapping(value = "/doSaveUserLastTheme", method = RequestMethod.POST)
	@ResponseBody
	public ApiResult doSaveUserLastTheme(HttpServletRequest request){
		Long userid = (Long) request.getSession().getAttribute(user);
        String lastTheme = request.getParameter("lastTheme");
        if(StringUtils.isEmpty(lastTheme)){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
        int result = 0;
        try {
            AdminInfo adminInfo = new AdminInfo();
            adminInfo.setAdmin_id(userid);
            adminInfo.setLast_theme(lastTheme);
            result = adminInfoService.update(adminInfo);
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        }
        if(result == 0){
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        }else{
            return new ApiResult(HttpResultEnum.SUCCESS.getCode(), "更新成功");
        }
    }

	/**
	 * 获取人员梁场列表
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getBeamFileList", method = RequestMethod.POST)
	@ResponseBody
	public ApiResult getBeamFileList(HttpServletRequest request){
		Long userId = (Long) request.getSession().getAttribute(user);
		Long beamId = (Long) request.getSession().getAttribute(beam);
		try{
			List<BeamFieldVo> beamFileList = beamFieldService.getBeamFileList(userId, beamId);
			return new ApiResult(beamFileList);
		}catch (Exception e){
			e.printStackTrace();
			return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
		}
	}


	/**
	 * 获取所有人员梁场列表
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getAllBeamFileList", method = RequestMethod.GET)
	@ResponseBody
	public ApiResult getAllBeamFileList(HttpServletRequest request){
		try{
			List<BeamFieldVo> beamFileList = beamFieldService.getAllBeamNameAndId();
			return new ApiResult(beamFileList);
		}catch (Exception e){
			e.printStackTrace();
			return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
		}
	}

	/**
	 * 选择梁场
	 * @return
	 */
	@RequestMapping(value = "/chooseBeamField", method = RequestMethod.POST)
	@ResponseBody
	public ApiResult chooseBeamField(HttpServletRequest request){
        String beamId = request.getParameter("beamId");
		Long userId = (Long) request.getSession().getAttribute(user);
        if(StringUtils.isEmpty(beamId)){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
        HttpSession session = request.getSession();
        try{
			BeamField beamField = beamFieldService.getBeamFieldVoByBeamId(Long.parseLong(beamId));
            session.setAttribute(beam,beamField.getBeam_id());
            session.setAttribute(beamName,beamField.getName());
            AdminInfo adminInfo = (AdminInfo) adminInfoService.getLoginInfo(userId).getResult();
			return new ApiResult(HttpResultEnum.SUCCESS.getCode(), HttpResultEnum.SUCCESS.getMessage(), adminInfo.getLast_theme());
		}catch (Exception e){
			e.printStackTrace();
			return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
		}

	}
}
